<?php
/**
 * File: Middleware.php.
 * User: Yan<me@xiaoyan.me>
 * DateTime: 2017-12-19 21:48
 */

namespace App\Core;

use App\Models\UserInfo;

class Middleware
{
    public static function Handle(Request $request)
    {
        $path = $request->getPath();
        if (!isset($_SESSION[WX_USER_KEY]) || !$_SESSION[WX_USER_KEY]) {
            //授权
            if (in_array($path,['/weixin/auth','/','/vote/item']) || self::isAdminPath($request)) {
                return true;
            }
            if($request->isAjax() && !$request->is_weixin()){
                ajaxError('请在微信中打开此页面');
            }
            jump(getFullUrl('/weixin/auth?callback=' . urlencode('/')));
            //jump(getFullUrl('/weixin/auth?callback=' . urlencode($request->getPath() . '?' . $request->query->raw())));
        }
        $request->openid = $_SESSION[WX_USER_KEY];
        $user = new UserInfo();
        if ($user->openidExists($_SESSION[WX_USER_KEY])) {
            if(($userData = $user->findByCondition(['user_open_id'=>$request->openid]))){
                $user->setProperty($userData);
                $request->user = $user;
                return true;
            }
        }
        if ($path == '/weixin/bind' || self::isAdminPath($request)) {
            return true;
        }
        jump(getFullUrl('/weixin/bind?callback=' . urlencode('/')));
    }
    private static function isAdminPath(Request $request){
        if (substr($request->getPath(),0,6) == '/admin') {
            return true;
        }
        return false;
    }
}